﻿<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: text/plain');

require_once "../../app/common.php";
require_once "WxPay.Api.php";
require_once "WxPay.Data.php";

$input = $_POST;

$type = $input['type'];// 1：余额充值，
switch ($type) {
    case 1:
        $user_id = $input['user_id'];
        if (checkUserStatus($user_id) === false) apiReturn(3, '您的账号已被禁用，请联系后台工作人员');
        $balance = $input['balance'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if ($balance <= 0) apiReturn(2, '充值金额有误，请重新输入');
        if ($balance != intval($balance)) apiReturn(2, '请输入整数充值金额');

        $balance_send_integral = array_reverse(array_values(array_filter(C('BALANCE_SEND_INTEGRAL'))));
        $send_integral = 0;
        if ($balance_send_integral) {
            foreach ($balance_send_integral as &$v) {
                $v = explode('/', $v);
                if ($balance >= $v[0]) {
                    $send_integral = $v[1];
                    break;
                }
            }
        }

        $user_info = Db::name('user')->where(['id' => $user_id])->find();

        $out_trade_no = createOrderSn();
        $data = [
            'user_id' => $user_id,
            'order_sn' => $out_trade_no,
            'pay_price' => $balance,
            'balance' => $balance,
            'send_integral' => $send_integral,
            'create_time' => time()
        ];
        Db::name('recharge_order')->insertGetId($data);

        $subject = '余额充值';
        $pay_price = $balance;
        $notify_url = getHost() . '/index/Notify/rechargeNotice';
        break;
}

// 微信支付
$unifiedOrder = new WxPayUnifiedOrder();
$unifiedOrder->SetNotify_url($notify_url);
$unifiedOrder->SetBody($subject);
$unifiedOrder->SetOut_trade_no($out_trade_no);
$unifiedOrder->SetTotal_fee($pay_price * 100);
$unifiedOrder->SetTrade_type("APP");
$result = WxPayApi::unifiedOrder($unifiedOrder);

if ($result['statusCode'] == 200) {
    apiReturn(1, '支付成功', $result['data']);
} else {
    apiReturn(2, '支付失败');
}

?>